package com.sansan.qiangji.controller.base;

import com.sansan.qiangji.VO.base.warehouse.WarehouseVO;
import com.sansan.qiangji.enums.ResultEnum;
import com.sansan.qiangji.exception.ServiceException;
import com.sansan.qiangji.form.base.WarehouseAddForm;
import com.sansan.qiangji.form.base.WarehouseEditForm;
import com.sansan.qiangji.form.base.WarehouseListForm;
import com.sansan.qiangji.realize.base.WarehouseReal;
import com.sansan.qiangji.resultVO.ResultVO;
import com.sansan.qiangji.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

@CrossOrigin()
@RestController
@RequestMapping("/warehouse")
@Slf4j
public class WarehouseController {
    @Autowired
    private WarehouseReal warehouseReal;

    @PostMapping("/addWarehouse")
    public ResultVO<Object> addWarehouse(@Valid @RequestBody WarehouseAddForm warehouseAddForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【仓库新增】参数不正确，warehouseAddForm={}",warehouseAddForm);
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        warehouseReal.addWarehouse(warehouseAddForm);
        return ResultVOUtil.success(null);
    }

    @PostMapping("/getWarehouseList")
    public ResultVO<Object> getWarehouseList(@Valid @RequestBody WarehouseListForm form, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【仓库查询】参数不正确，warehouseAddForm={}",form);
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        return ResultVOUtil.success(warehouseReal.warehouseList(form));
    }

    @GetMapping("/getAllWarehouse")
    public ResultVO<Object> getAllWarehouse() {
        List<WarehouseVO> warehouseVOS = warehouseReal.getAllWarehouse();
        return ResultVOUtil.success(warehouseVOS);
    }

    @PostMapping("/editWarehouse")
    public ResultVO<Object> editWarehouse(@Valid @RequestBody WarehouseEditForm warehouseEditForm, BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            log.error("【仓库修改】参数不正确，warehouseAddForm={}",warehouseEditForm);
            throw new ServiceException(ResultEnum.PARAM_ERROR.getCode(), Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        warehouseReal.editWarehouse(warehouseEditForm);
        return ResultVOUtil.success(null);
    }

    @PostMapping("/deleteWarehouse")
    public ResultVO<Object> deleteWarehouse(@RequestParam(value = "warehouseId") Integer warehouseId){
        warehouseReal.deleteWarehouse(warehouseId);
        return ResultVOUtil.success(null);
    }


}
